import socket,time
import sys
from threading import Thread
from Queue import Queue

class ConnectionMonitor(Thread):
    def __init__(self, ip, port, connections):
        self.ip=ip
        self.port=port
        self.connections=connections
        Thread.__init__(self)
    def run(self):
        sys.stdout.write("Running")
        while 1:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind((self.ip,self.port))
            s.listen(1)
            conn, addr = s.accept()
            print "connected to client @", addr
            self.connections.put(conn)

class ServerPipe(object):
    def __init__(self,ip,port):
       self.ip = ip
       self.port = port
       self.connections=Queue()
    def startConnection(self):
        sys.stdout.write("starting")

        
        self.cm=ConnectionMonitor(self.ip,self.port, self.connections)
        self.cm.start()
        sys.stdout.write("Connection started")
    
    
#     def setPlayerInfo(self):
#         #while 1:
#             data = self.conn.recv(1024)
#             self.dataList.append(data)
#             #if not data: return None
#             #self.conn.send(data)
#             sys.stdout.write(str(self.dataList))
#             data2 = self.conn.recv(1024)
#             self.dataList.append(data2)
#             if not data: return None
#             #self.conn.send(data)
#             sys.stdout.write(str(self.dataList))
#             #if not data:break
#             self.conn.close()
# #            pipe.recvData()
            
#     def recvData(self):
#         while 1:
#             data = self.conn.recv(1024)
#             if not data: return None
#             self.conn.send(data)
#             sys.stdout.write(str(data))
#             #return data
#             if not data:break
#         conn.close()

    def closeConnection(self):
        self.conn.close()

    def requestData(self, item):
        self.conn.send(item)    
        
if __name__ == "__main__":
    ip = ""
    port = 1234
    sys.stdout.write("Beginning")
    sys.stdout.flush()
    p=ServerPipe(ip,port)
    sys.stdout.write("Starting outside")
    p.startConnection()
    while True:
        sys.stdout.flush()
        print "Connections:"
        for i in p.connections.queue:
            print i
        sys.stdout.write(str(p.connections))
        time.sleep(2)

    #sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #pipe = Pipe(ip,port)
    #pipe.startConnection(ip,port)
    #pipe.recvData()
    #pipe.requestData('testing')
    #pipe.closeConnection()
    #data = conn.recvData()
    #sys.stdout.write(item)
    
    
